<template>
  <div class="pageContent" v-if="1">
    <image class="loginIm" :src="images +'/loginBack.png'"></image>
    <view class="loginTap">
      <image class="loginIc" :src="localImages +'/mainIcon.png'" @click="doubleClick"></image>
      <view class="loginTil">世纪金源服务集团有限公司</view>
    </view>
    <view class="loginCom">
      <image class="loginTeIm" :src="images +'/loginText.png'" mode="widthFix"></image>
      <view class="loginComTe">全国服务热线：400-991-5888</view>
    </view>

		<view class="handler">
			<button class="btOne btDefalt" @click="returnMain">取消</button>
			<button class="btOne" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">微信登录</button>
		</view>
    <!-- <button class="btOne" open-type="getUserInfo" @getuserinfo="getUser">微信授权登</button> -->
    <view class="modal-content show" v-if="showModal">
      <view class="modal-box" style="height:220rpx; text-align: center;">
        <view>开启调试模式</view>
        <input class="memberItIn" placeholder-class="inputPlaceHold" v-model="secrect" placeholder="请输入调试密码"/>
        <view class="modalBot modalCancel" >
          <view  class="btnConfirm btnCancel" @click='onCancel'>取消</view>
          <view class="btnConfirm" @click='onConfirm'>确定</view>
        </view>
      </view>

    </view>
  </div>
</template>

<script>
import { mapState } from 'vuex'
// import { genTestUserSig } from '../../../static/utils/GenerateTestUserSig'
import util from '../../../static/utils/util.js'
import config from '../../../static/config.js'
export default {
  data () {
    return {
      images: config.images,
      localImages: config.localImages,
      showModal: false,
      secrect: '',
    }
  },
  computed: {
    ...mapState({
      myInfo: state => state.user.myInfo
    })
  },
  onLoad(){
    //在登录界面先获取下session信息，避免登录时，后台无法获取手机号
    this.getOpenId();
  },
  onShow(){
  },
  methods: {
    returnMain(){
      wx.switchTab({ url: '/pages/index/main' })
    },
    getOpenId(){
      return new Promise((resolve,reject)=>{
        this.wxLogin().then((res)=>{
          var jsCode = res.code
          // var url='/UserServer/weChat/getWxCode2Session' //通过 wx.login 接口获得临时登录凭证 code 授权
          var url='/UserServer/weChat/getStaffWxCode2Session' //通过 wx.login 接口获得临时登录凭证 code 授权
          var params={
            js_code :jsCode
          }
          util.wxRequestPro(url,params).then((res)=>{
            console.warn('getWxCode2Session',res)
            var param=res.param
            wx.setStorageSync('openId', param.openid);
            resolve()
          }).catch((res)=>{
            console.warn('res=catch',res)
          })
        })
      })
    },
    wxLogin() {
      return new Promise((resolve,reject)=>{
        wx.login({
          complete: (res) => {
            resolve(res)
          },
        })
      })
    },
    //获取用户手机号码
    getPhoneNumber(userInfo) {
        let self = this;
        console.warn('userInfo', userInfo);
        console.warn('userInfo', userInfo.mp.detail);
        var phoneInfo=userInfo.mp.detail
        if(!phoneInfo.iv){
          wx.showToast({
            title: '请允许授权登录',
            icon: 'none',
            duration: 1000
          })
          return
        }
        wx.removeStorageSync('token') //移除token，登录接口util工具共用
        wx.login({
            complete: (res) => {
                var jsCode = res.code
                // var url='/UserServer/weChat/getWxUserOpenId'
                var url='/UserServer/weChat/getStaffWxUserOpenId' //获取用户加密的openid unionid 信息
                var params={
                  encryptedData: phoneInfo.encryptedData,
                  iv :phoneInfo.iv,
                  js_code :jsCode
                }
                util.wxRequestPro(url,params).then((res)=>{
                  console.warn('getWxUserOpenId',res)
                  var param=res.param;
                  if(param){
                    var phoneNumber=param.phoneNumber;
                    // var phoneNumber=18075153830;//测试登录手机号
                    if(phoneNumber){
                      wx.setStorageSync('phone', phoneNumber);
                      this.noticeList()
                    }
                  }else {
                    if(res.statusCode==200){
                      wx.showToast({
                          title: '请重新获取手机号',
                          icon: 'none'
                      })
                    }
                    if(res.statusCode==400){
                      wx.showToast({
                          title: res.statusInfo,
                          icon: 'none'
                      })
                    }
                  }
                })
            },
        })
    },

    ownerRoomList(phoneNumber){
      //获取业主该手机号绑定的房屋列表
      var params={telephone :phoneNumber}
      util.wxRequestPro('/UserServer/room/ownerRoomList',params)
      .then((res)=>{
        console.warn('ownerRoomList',res)
        var param=res.param;
        //未录入用户
        if(!param){
          //清空room列表
          this.$store.commit('updateRoomlist', [])
          wx.redirectTo({ url: '/pages/subMe/houseList/main' })
        }
        //用户有多个房屋
        // else if(param.length>1){
        //   //缓存room列表
        //   this.$store.commit('updateRoomlist', param)
        //   wx.redirectTo({ url: '/pages/subMe/houseList/main' })
        // }
        // else if(param.length==1){
        //   var room=param[0];
        //   this.noticeList(room)
        // }

      }).catch((res)=>{
        console.warn('ownerRoomList',res)
        if(res.statusCode==400) {
          wx.showToast({
              title: '手机没有绑定房屋',
              icon: 'none'
          })
        }
      })
    },

    noticeList(room) {
      return new Promise((resolve,reject)=>{
        // /weChat/staffLogin 小程序物业获取登录令牌
        var url='/UserServer/weChat/staffLogin'
        var phone=wx.getStorageSync('phone');
        var openId=wx.getStorageSync('openId');
        var userInfo=wx.getStorageSync('userInfo');
        var params={"telephone":phone,"roomIdNow":0,"openId":openId,"portraitUrl":userInfo.avatarUrl}
        // var params={"telephone":"18373086780","roomIdNow":"6","openId":"otS_J5BacQniO0hwPeE_o0yC42Wo"}
        util.wxRequestPro(url,params,"POST").then((res)=>{
          console.warn('ownerLogin',res)
          var param =res.param
          wx.setStorageSync('room', room);
          wx.setStorageSync('userMsg', param);

          wx.switchTab({ url: '/pages/index/main' })
          // wx.reLaunch({ url: '/pages/index/main' })
        }).catch((res)=>{
          console.warn('catch=ownerLogin',res)
        })
      })
    },

    getUser(e) {
      console.warn(e)
      let that = this;
      wx.getSetting({
        success(res) {
          console.warn('getSetting-success',res)
          if (res.authSetting['scope.userInfo']) {
            that.getuserinfo();
          } else {
            wx.authorize({
              scope: 'scope.userInfo',
              success() {
                that.getuserinfo();
              }
            })
          }
        },
        fail(res){
          console.warn('fail-success',res)
        },
      })
    },
    getuserinfo() {
      let that = this;
      wx.getUserInfo({
        success: function (res) {
          console.warn(res);
        },
        fail: () => {
          wx.showToast({
            title: '获取用户信息失败',
            icon: 'none',
            duration: 3000
          })
        }
      })
    },

    // 点击登录进行初始化
    handleLogin() {
      var userMsg=wx.getStorageSync('userMsg');
      if(userMsg) {
        var userID = userMsg.im_userId
        // case1: 要登录的用户是当前已登录的用户，则直接跳转即可
        console.warn('this.myInfo',this.myInfo,this.myInfo.userID,userID)
        if (this.myInfo.userID && userID === this.myInfo.userID) {
          wx.reLaunch({ url: '/pages/index/main' })
          return
        }
        // case3: 正常登录流程
        this.login(userMsg)
      }else {
        wx.reLaunch({ url: '/pages/index/main' })
      }
    },
    login(userMsg) {
      // var userID = 'user2'
      // let userSig = genTestUserSig(userID).userSig
      var userID = userMsg.im_userId
      var userSig = userMsg.userSig
      wx.$app.login({
        userID:userID,
        userSig: userSig
      }).then((res) => {
        console.warn('login=',res)
        this.$store.commit('setRtcConfig', {userID: userID, userSig: userSig, sdkAppID: wx.$sdkAppID})
        wx.reLaunch({ url: '/pages/index/main' })
        // wx.switchTab({ url: '/pages/index/main' })
      }).catch(() => {
        wx.reLaunch({ url: '/pages/index/main' })
      })
    },

    doubleClick(e) {
      //e.timeStamp：当前点击时的毫秒数；
      // this.touchStartTime： 储存上一次点击时的毫秒数，默认0
      console.warn('单击', this.touchStartTime, this, e);
      if (e.timeStamp - this.touchStartTime < 300) {
        // 双击，进入
        console.warn('双击，进入', this.touchStartTime, this);
        this.showModal=true;
      }
      this.touchStartTime = e.timeStamp;
    },

    onCancel(){
      this.showModal=false;
    },
    onConfirm(){
      if(this.secrect=='666'){
        wx.navigateTo({
            url: '/pages/subMe/test/main',
        })
      }else {
        wx.showToast({
          title: '密码错误',
          icon: 'none',
          duration: 1000
        })
      }
    },

  }
}
</script>

<style lang="stylus" scoped>
.pageContent{

}
.loginIm{
  width 630rpx
  height 456rpx
  margin 100rpx 0rpx 150rpx 60rpx
}
.loginTap{
  display flex
  justify-content center
}
.loginIc{
  width 50rpx
  height 50rpx
  margin-right 16rpx
}
.loginTil{
  font-size 42rpx
  font-weight bold
  color: #333333;
  font-family: HanziPenSC;
}
.loginCom{
  display flex
  flex-direction column
  align-items center
  justify-content center
}
.loginTeIm{
  // position absolute
  width 220rpx;
  height 40rpx;
  // left 50%
  // margin-left -185rpx;
  margin-top 38rpx
}
.loginComTe{
  font-size: 26rpx;
  color: #1086FF;
  margin-top 24rpx
}
.handler {
  margin-top: 100rpx;
  display: flex;
  justify-content: space-between;
  // padding: 0 60rpx;
  box-sizing: border-box;
  width: 100%;
}
.btOne{
  width 330rpx;
  font-weight bold
}
.btOne.btDefalt{
  background #DDDDDD;
  color: #1086FF;
      box-shadow: 0px 13rpx 29rpx 0px #DDDDDD;
}

.modal-content {
    position: fixed;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    z-index: 999;
    text-align: left;
    background-color: rgba(0, 0, 0, 0.2);
}

.modal-box {
    position: absolute;
    left: 50%;
    opacity: 0;
    top: 300rpx;
    width: 650rpx;
    height: 590rpx;
    border-radius: 24rpx;
    margin-left: -325rpx;
    background-color: #fff;
    transition: opacity 0.2s ease-in;
}

.modal-content.show .modal-box {
    opacity: 1;
}

.modalBot {
    position: absolute;
    display: flex;
    width: 460rpx;
    height: 110rpx;
    bottom: 0;
    left: 50%;
    margin-left: -230rpx;
    line-height: 80rpx;
    z-index: 99;
    /* border: 1rpx solid coral; */
}

.modalCancel{
    width: 600rpx;
    margin-left: -300rpx;
}

.btnConfirm {
    flex: 1;
    height: 80rpx;
    color: #fff;
    font-size: 28rpx;
    line-height: 80rpx;
    text-align: center;
    border-radius: 8rpx;
    background-color: #1A76FF;
}

.btnCancel {
    background-color: #ccc;
    margin: 0rpx 20rpx 0rpx 0rpx;
}

.close-modal {
    position: absolute;
    bottom: -140rpx;
    left: 50%;
    width: 64rpx;
    height: 64rpx;
    margin-left: -32rpx;
    z-index: 99;
}

</style>
